package com.example.anydo.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.anydo.R;

import com.example.anydo.adapter.EditSubTaskAdapter;
import com.example.anydo.adapter.ListViewAdapter;
import com.example.anydo.bean.ItemBean;
import com.example.anydo.bean.SubTaskBean;
import com.example.anydo.bean.TaskBean;
import com.example.anydo.bean.UserBean;
import com.example.anydo.service.TimeTaskService;
import com.example.anydo.util.database.DatabaseHelper;
import com.example.anydo.util.pub_util.SPUtil;
import com.example.anydo.util.pub_util.Util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
//hxy create in 2021.06.21

public class EditTaskActivity extends AppCompatActivity {

    private TaskBean mData;

    private TextView tv_date,tv_usr;
    
    private  ImageButton btn_setAlarm,btn_setRept;
    private RecyclerView rv_subTodo;
    private EditSubTaskAdapter mAdapter;
    
    //et_title从前一个activity获取usr
    private EditText et_title,et_description;
    
    private String userId;
    private DatabaseHelper dbHelper;
    
    public static final int SAVE_NEW = 1;
    public static final int SAVE_UPDATE = 2;
    private int saveType = -1;


    //private Button btn_now,btn_tom,btn_selectDate,btn_setTodo;
    private Button[] dates = new Button[4];

    private String time = "";

    Intent mAlarmIntent = null;
    TimeTaskService mTimeTaskService;
    private TimeTaskService.TimeTaskBinder binder;
    boolean bound = false;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("TAG", "onServiceConnected: ========" );
            binder = (TimeTaskService.TimeTaskBinder)service;
            mTimeTaskService = binder.getService();
            bound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bound = false;
        }
    };
    
    public static void actionStart(Context context, TaskBean data,int saveType){
        Intent intent = new Intent(context,EditTaskActivity.class);
        intent.putExtra("task", data);
        intent.putExtra("type",saveType);
        context.startActivity(intent);
    }

    public void initView(){
        rv_subTodo= findViewById(R.id.rv_subTodo);
        tv_date=(TextView)findViewById(R.id.tv_date);
        tv_usr=(TextView)findViewById(R.id.tv_usr);
        et_title=(EditText) findViewById(R.id.et_title);
        et_description=(EditText)findViewById(R.id.et_description);
        dates[0]=(Button) findViewById(R.id.btn_now);
        dates[1]=(Button) findViewById(R.id.btn_tom);
        dates[2]=(Button) findViewById(R.id.btn_selectDate);
        dates[3]=(Button) findViewById(R.id.btn_setTodo);
        btn_setAlarm=(ImageButton) findViewById(R.id.btn_setAlarm);
        btn_setRept=(ImageButton) findViewById(R.id.btn_setRept);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_task);

        dbHelper = new DatabaseHelper(this);

        //mAlarmIntent = new Intent(this , TimeTaskService.class);

        bindService(new Intent(this,TimeTaskService.class),
                connection, Context.BIND_AUTO_CREATE);
        //startService(mAlarmIntent);


        //初始化构件
        initView();
        initData();
        initSettings();

    }//onCreate

    private void initSettings(){
        mAdapter = new EditSubTaskAdapter(mData.getData().getSubTasks(),this);
        rv_subTodo.setAdapter(mAdapter);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        rv_subTodo.setLayoutManager(layoutManager);
    }
    private void initData() {
        // 当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        tv_date.setText(simpleDateFormat.format(date));

        // user名称
        userId = SPUtil.getUserId(this);
        String name = dbHelper.getUserNameById(Integer.parseInt(userId));
        tv_usr.setText(name);

        // 任务id
        Intent intent = getIntent();
        saveType = (int) intent.getIntExtra("type",-1);
        
        // 新建任务
        if(saveType == SAVE_NEW){
            mData = new TaskBean();
            mData.setData(new TaskBean.DataBean());
            mData.getData().setDate(Util.getDayNow());
            mData.getData().setIfDone("否");
        }else if(saveType == SAVE_UPDATE){ // 编辑任务
            mData = (TaskBean) intent.getSerializableExtra("task");
            // 日期
            TaskBean.DataBean bean = mData.getData();
            et_title.setText(bean.getTitle());
            et_description.setText(bean.getDescription());
            if(bean.getDate().equals(Util.getDayNow())){
                changeDateButton(0,"");
            }else if(bean.getDate().equals(Util.nextDay())){
                changeDateButton(1,"");
            }else if(bean.getDate().equals("")){
                changeDateButton(3,"");
            }else {
                changeDateButton(2,Util.getDate(bean.getDate()));
            }
            
            // 提醒时间
            if(!bean.getTime().equals("")){
                btn_setAlarm.setBackgroundResource(R.drawable.button_shape_green);
            }
            
            // 重复
            if(!bean.getRate().equals("")){
                btn_setRept.setBackgroundResource(R.drawable.button_shape_green);
            }
            
        }else {
            Log.e("TAG", "edit task intent error!" );
        }

    }

    /* hxy,6.21
* 点击事件定义*/

    //保存按键点击，保存数据，同时返回主页面
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void save_click(View view) {
        mData.getData().setTitle(et_title.getText().toString());
        mData.getData().setDescription(et_description.getText().toString());
        mData.getData().setRate("20210621");
        mData.getData().setSubTasks(mAdapter.getSubTasks());
        Log.i("TAG", "save_click: " + mData.toString());
        if(saveType == SAVE_UPDATE){
            Log.e("DatabaseHelper", "save_click: "+"update" );
            if(dbHelper.saveTask(Integer.parseInt(userId),mData,false)){
                finish();
            }
        }else if (saveType == SAVE_NEW){
            Log.e("DatabaseHelper", "save_click: "+"new" );
            if(dbHelper.saveTask(Integer.parseInt(userId),mData,true)){
                if(!mData.getData().getTime().equals("")){
                    mTimeTaskService.addTask(mData);
                    mTimeTaskService.startAlarm();
                }

                finish();
            }

        }else {
            Util.toast(this,"创建失败，saveType=" + saveType);
        }

    }

    //叉号点击事件，直接返回主页面
    public void return_click(View view) {
        AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("当前任务未保存，是否放弃")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })

                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create();
        if(et_title.getText().equals("")){
            finish();
        }else {
            alertDialog2.show();
        }
    }

    private void changeDateButton(int day,String date){
        for(int i = 0; i<4; i++){
            dates[i].setBackgroundResource(R.drawable.button_shape_gray);
        }
        dates[day].setBackgroundResource(R.drawable.button_shape_green);
        if (!date.equals("")){
            dates[2].setText(date);
        }
        
    }
    
    //今天点击事件，设置颜色，修改时间字段
    public void today_click(View view) {
        changeDateButton(0,"");
        mData.getData().setDate(Util.getDayNow());
    }


    //明天点击事件，设置颜色，修改时间字段

    public void tomorrow_click(View view) {
        mData.getData().setDate(Util.nextDay());
        changeDateButton(1,"");
    }

    //选择日期点击事件，修改button的显示内容，修改时间字段
    public void selectDate_click(View view) {
        Calendar ca = Calendar.getInstance();
        int mYear = ca.get(Calendar.YEAR);
        int mMonth = ca.get(Calendar.MONTH);
        int mDay = ca.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dlg = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = "";
                        if (month + 1 < 10) {
                            if (dayOfMonth < 10) {
                                date = new StringBuffer().append(year).append("0").append(month + 1).append("0").append(dayOfMonth).toString();
                            } else {
                                date = new StringBuffer().append(year).append("0").append(month + 1).append(dayOfMonth).toString();
                            }

                        } else {
                            if (dayOfMonth  < 10) {
                                date = new StringBuffer().append(year).append(month + 1).append("0").append(dayOfMonth).toString();
                            } else {
                                date = new StringBuffer().append(year).append(month + 1).append(dayOfMonth).toString();
                            }

                        }

                       // Util.toast(EditTaskActivity.this,"设置日期"+date);
                        changeDateButton(2,month+1 + "." + dayOfMonth);
                        mData.getData().setDate(date);

                    }
                }, mYear, mMonth, mDay);
        dlg.show();
        
    }

    //待办项点击事件，修改button的颜色，修改时间字段为空
    public void toDo_click(View view) {
        changeDateButton(3,"");
        mData.getData().setDate("");
    }

    //时钟点击事件，修改button的显颜色，修改时间字段
    public void alarm_click(View view) {
        Calendar calendar= Calendar.getInstance(Locale.CHINA);
        new TimePickerDialog( this,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        btn_setAlarm.setBackgroundResource(R.drawable.button_shape_green);
                        String time = "";
                        if(hourOfDay<10){
                            time += "0" + hourOfDay;
                        }else {
                            time+=hourOfDay;
                        }
                        if(minute<10){
                            time += "0" + minute;
                        }else {
                            time+=minute;
                        }
                        mData.getData().setTime(time);
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }

    //重复点击事件，修改button的显颜色，修改时间字段
    public void repeat_click(View view) {
        btn_setRept.setBackgroundResource(R.drawable.button_shape_green);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}//class

